E) Operator

연산자 오버로딩(Operator Overloading)
nb1+nb2=nb1.operator+(nb2)
#include <iostream>
class NUMBOX{
private:
int num1, num2;
public:
NUMBOX(int num1, int num2): num1(num1), num2(num2) {}
void showNum(void){
std::cout<<"num1: "<<num1<<", num2: "<<num2<<std::endl;
}
NUMBOX operator+(NUMBOX& ref){
return NUMBOX(num1+ref.num1, num2+ref.num2);
}
};
NUMBOX 클래스와 다른 클래스 사이의 연산자를 정의할 수 있다.

int+NUMBOX는 NUMBOX 클래스 내에서 연산자 정의할 수 없다.
int.operator+(NUMBOX)
전역 함수 오버로딩
피연산자+피연산자=operator+(피연산자, 피연산자)
#include <iostream>
class NUMBOX{
private:
int num1, num2;
public:
NUMBOX(int num1, int num2): num1(num1), num2(num2) {}
void showNum(void){
std::cout<<"num1: "<<num1<<", num2: "<<num2<<std::endl;
}
NUMBOX operator+(int num){
return NUMBOX(num1+num, num2+num);
}
friend NUMBOX operator+(int num, NUMBOX ref);
};
NUMBOX operator+(int num, NUMBOX ref){
ref.num1+=num;
ref.num2+=num;
return ref;
}
단항 연산자 오버로딩
증가, 증감 연산자(전위, 후위)
#include <iostream>
class NUMBOX{
private:
int num1, num2;
public:
NUMBOX() {}
NUMBOX(int num1, int num2): num1(num1), num2(num2) {}
void showNum(void){
std::cout<<"num1: "<<num1<<", num2: "<<num2<<std::endl;
}
NUMBOX operator++(){
num1+=1;
num2+=1;
return *this;
}
NUMBOX operator++(int){
NUMBOX temp(*this);
num1+=1;
num2+=1;
return temp;
}
};
int main(void){
NUMBOX nb1(10, 20);
NUMBOX nb2;
nb2=nb1++;
nb1.showNum();
nb2.showNum();
nb2=++nb1;
nb1.showNum();
nb2.showNum();
return 0;
}

num1: 11, num2: 21

num1: 10, num2: 20

num1: 12, num2: 22

num1: 12, num2: 22

++nb=nb.operator++(); // 전위 증가 연산자
nb++=nb.operator++(int); // 후위 증가 연산자
후위 증가 연산자의 int는 실제 데이터 타입을 의미하는 것이 아닌 전위 증가와 후위 증가를 구분하기 위한 용도
대입 연산자 오버로딩
대입 연산자를 별도로 생성해 주지 않아도 default로 대입 연산자는 생성이 됨
하지만, default 대입 연산자는 얕은 복사만 진행함
#include <iostream>
#include <string>
class Student{
private:
char* name;
int age;
public:
Student(char* name, int age): age(age){
this->name=new char[10];
std::strcpy(this->name, name);
}
void showInfo(void){
std::cout<<"NAME: "<<name<<std::endl;
std::cout<<"AGE: "<<age<<std::endl;
}
Student& operator=(Student& ref){
delete[] name;
name=new char[10];
strcpy(name, ref.name);
age=ref.age;
return *this;
}
~Student(){
delete[] name;
std::cout<<"~Student Destrutor"<<std::endl;
}
};
int main(void){
Student st1((char*)"KIM", 14);
Student st2((char*)"HONG", 15);
st2=st1;
st1.showInfo();
st2.showInfo();
return 0;
}